﻿using System;
using System.IO;
using System.Text;

namespace Azure.Online.Proxy.Server {
    public class HttpServerChunkedResponseStream : HttpServerResponseStream {
        private long _position;

        public HttpServerChunkedResponseStream(HttpServerContext context, Stream inner)
            : base(context, inner, 0) {
        }

        public override void Flush() {
            _inner.Write(new byte[] { 48, 13, 10, 13, 10 }, 0, 5);
            _inner.Flush();
        }

        public override void Write(byte[] buffer, int offset, int count) {
            var chunk = new byte[2048];
            while (count > 0) {
                var chunkSize = count < chunk.Length ? count : chunk.Length;
                var chunkHeader = Encoding.UTF8.GetBytes(chunkSize.ToString("x").ToUpperInvariant() + "\r\n");
                _inner.Write(chunkHeader, 0, chunkHeader.Length);
                _inner.Write(buffer, offset, chunkSize);
                _inner.Write(new byte[] {13, 10}, 0, 2);

                offset += chunkSize;
                count -= chunkSize;
                _position += chunkSize;
            }
        }

        public override long Position {
            get { return _position; }
            set {
                throw new InvalidOperationException();
            }
        }

        public override long Length {
            get { return _position; }
        }
    }
}
